package com.opdar.platform.core.base;

import java.util.*;

/**
 * Created by shiju on 2017/1/17.
 */
public class RouterManager {

    private static List<Router> routers = new ArrayList<Router>();
    private static List<RestRouter> restRouters = new ArrayList<RestRouter>();
    private static ThreadLocal<Router> currentRouter = new ThreadLocal<Router>();

    public static void setCurrentRouter(Router router) {
        currentRouter.set(router);
    }

    public static Router getCurrentRouter() {
        return currentRouter.get();
    }

    public static void clearCurrentRouter() {
        currentRouter.remove();
    }

    public static int add(Router router){
        if(router instanceof RestRouter){
            if(!restRouters.contains(router)){
                restRouters.add((RestRouter) router);
            }
        }else if(!routers.contains(router)){
            routers.add(router);
            return routers.size();
        }
        return -1;
    }


    public static void sort(){
        Collections.sort(restRouters, new Comparator<RestRouter>() {
            @Override
            public int compare(RestRouter o1, RestRouter o2) {
                return o1.getMappingSize()>o2.getMappingSize()?1:-1;
            }
        });
    }

    public static Router get(Router router) {
        int index = routers.indexOf(router);
        if(index >= 0){
            return routers.get(index);
        }else{
            for (RestRouter _router : restRouters) {
                Map<String, Object> parameters = new HashMap<String, Object>();
                boolean ret = _router.match(router.getName(), parameters);
                if (ret) {
                    return _router;
                }
            }
        }
        return null;
    }

    public static boolean contains(Router router,Map<String, Object> parameters) {
        boolean ret = routers.contains(router);
        if(!ret){
            for (RestRouter _router : restRouters) {
                ret = _router.match(router.getName(), parameters);
                if (ret) {
                    break;
                }
            }
        }
        return ret;
    }

    public static Router get(String name,int version) {
        Router o = new Router(name);
        o.setVersion(version);
        return routers.get(routers.indexOf(o));
    }

    public static boolean contains(String name,int version) {
        Router router = new Router(name);
        router.setVersion(version);
        return routers.contains(router);
    }
}
